繁体   English   中英

React项目不在Windows上运行但在ubuntu上运行

[英]React project not running on windows but runs on ubuntu

我已经在计算机中导入了反应项目。 当我尝试运行gulp命令时,它在控制台中给我一个错误。 但是与此同时,当我在ubuntu上运行它时,它的工作原理也很好。 这是我在Windows上遇到的错误

ERROR in ./src/client/index.js
Module parse failed: D:\Frontend-Master\src\client\index.js Unexpected token (64:2)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (64:2)
    at Parser.pp$4.raise (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:2221:15)
    at Parser.pp.unexpected (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1597:21)
    at Parser.pp$3.parseExprList (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:2165:22)
    at Parser.pp$3.parseSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1741:35)
    at Parser.pp$3.parseExprSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1718:17)
    at Parser.pp$3.parseMaybeUnary (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1597:21)
    at Parser.pp$3.parseExpression (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1573:21)
 @ multi main
  -- client bundled.
Hash: f58f7ad4ec2f7df577bf
Version: webpack 1.13.3
Time: 853ms
           Asset     Size  Chunks             Chunk Names
server-bundle.js  24.5 kB       0  [emitted]  main
  -- server:watch bundled.
[14:53:35] Finished 'bundle' after 946 ms
[14:53:35] Starting 'start:server'...
Starting Node Server...
[14:53:36] Finished 'start:server' after 1.23 s
[14:53:36] Starting 'watch:sync'...
webpack built 7a9966082c49871875b8 in 386ms
Hash: 7a9966082c49871875b8
Version: webpack 1.13.3
Time: 386ms
         Asset     Size  Chunks       Chunk Names
main-bundle.js  99.3 kB       0       main

ERROR in ./src/client/index.js
Module parse failed: D:\Frontend-Master\src\client\index.js Unexpected token (64:2)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (64:2)
    at Parser.pp$4.raise (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:2221:15)
    at Parser.pp.unexpected (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1597:21)
    at Parser.pp$3.parseExprList (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:2165:22)
    at Parser.pp$3.parseSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1741:35)
    at Parser.pp$3.parseExprSubscripts (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1718:17)
    at Parser.pp$3.parseMaybeUnary (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1597:21)
    at Parser.pp$3.parseExpression (D:\Frontend-Master\node_modules\acorn\dist\acorn.js:1573:21)
 @ multi main

这是我的index.js文件

var debug = require('debug')('tes:client')

window.Promise = Promise;
window.$ = window.jQuery = $;
injectTapEventPlugin();

var browserHistory = useRouterHistory(createHistory)({
    queryKey: false,
    basename: '/'
});

var initialState = window.INITIAL_STATE || {};

var store   = configureStore(initialState, browserHistory);
var routes  = getRoutes(store);
var history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router
});

const ROOT_CONTAINER = document.getElementById('root');
const onRenderComplete = ()=> {
    console.timeEnd('render');
}

if ( __DEV__ ){
    window._STORE = store;
    window.React = React;
    window.ReactDOM = ReactDOM;
}
window.localStorage.debug = 'tessact:*'
window._History = history

let muiTheme = getMuiTheme(theme);

console.time('render');
match({ history, routes }, (error, redirectLocation, renderProps) => {
    ReactDOM.render(
        <MuiThemeProvider muiTheme={muiTheme}>
            <Root store={store}>
                <WithStylesContext onInsertCss={styles=> styles._insertCss()}>
                    <Router {...renderProps} />
                </WithStylesContext>
            </Root>
        </MuiThemeProvider>,
        ROOT_CONTAINER,
        onRenderComplete
    )
});

这是我的client.config.js文件

var path = require('path');
var webpack = require('webpack');

var DIRS = require('./dirs.js');

var stylus = require('stylus');
var nib = require('nib');
var axis = require('axis');
var rupture = require('rupture');
var bootstrap = require('bootstrap-styl');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var IS_PROD = process.env.NODE_ENV === "production";
var config = {
    devtool: IS_PROD ? false : 'eval',
    debug: !IS_PROD,
    cache: true,
    root: DIRS.ROOT,
    watchOptions: {
        ignored: /node_modules/
    },
    entry: {
        main: [ DIRS.SRC_CLIENT + '/index.js' ]
    },
    output: {
        path: DIRS.BUILD_PUBLIC,
        publicPath: '/public/',
        filename: '[name]-bundle.js'
    },
    resolve: {
        modulesDirectories: [ DIRS.SRC_CLIENT, 'node_modules'],
        extensions: ['', '.webpack.js', '.web.js', '.js', '.styl'],
    },
    module: {
        loaders: [
            {test: /\.json$/, loader: 'json', exclude: /node_modules/},
            {test: /\.js$/, 
                loader: 'babel', 
                exclude: /node_modules/,
                include: [ DIRS.SRC_CLIENT ],
                query: {
                    cacheDirectory: true,
                    env: { 
                        development: {
                            presets: ['react-hmre']
                        }
                    } 
                }
            },
            {
                test: /\.styl$/, 
                loader: [ 
                    'isomorphic-style-loader',
                    'css?sourceMap&localIdentName=[name]_[local]_[hash:base64:3]',
                    'stylus?sourceMap'
                ].join('!')
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff'
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file-loader'
            },{
                test: /\.(png|jpg|jpeg|gif)$/,
                loader: 'url-loader',
                query: {
                  name: IS_PROD ? '[hash].[ext]' : '[path][name].[ext]?[hash]',
                  limit: 10000,
                }
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            __DEV__: !IS_PROD,
            __SERVER__: false,
            "process.env.NODE_ENV": (IS_PROD ? JSON.stringify("production") : JSON.stringify("development"))
        }),
        new webpack.ProvidePlugin({
            React: 'react'
        }),
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/)
    ],
    stylus: {
        use: [nib(), axis(), rupture(), bootstrap()],
        import: path.resolve(__dirname, '../src/stylus/index.styl'),
        error: IS_PROD,
        compress: IS_PROD,
        'include css': true
    }
};

if (IS_PROD){
    // console.log('--- CLIENT:PRODUCTION_MODE ---');
    config.entry.vendors = [
        'react', 'react-dom', 'react-router',
        'lodash', 'core-js', 'moment', 'jquery', 'bluebird',
        'redux', 'react-redux', 'react-router-redux',
        'history'
    ];

    config.plugins = config.plugins.concat([  
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors-bundle.js'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {warnings: false},
            comments: false
        }),
        new webpack.optimize.AggressiveMergingPlugin(),
    ]);
} else {
    config.entry.main.unshift('webpack-hot-middleware/client')
    config.plugins = config.plugins.concat([
        new webpack.DllReferencePlugin({
            context: DIRS.SRC_CLIENT,
            manifest: require(DIRS.BUILD_PUBLIC + '/dll/vendor-manifest.json')
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]);
}


module.exports = config;

这是package.json中的脚本

 "main": "index.js",
  "scripts": {
    "postinstall": "set NODE_ENV=production node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod",
    "start": "node build/server-bundle.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

我也没有附加server.config.js文件,因为认为没有必要。 这些代码的所有内容都可以在Ubuntu中运行。

Shubham Khatri回答后出错。 我在评论他的答案时都运行了这两个命令。

> cross-env NODE_ENV=prod & node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod

D:\Frontend-Master\node_modules\.bin\gulp:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^
SyntaxError: missing ) after argument list
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.0.17: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN tessact@0.0.1 No repository field.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! tessact@0.0.1 postinstall: `cross-env NODE_ENV=prod & node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the tessact@0.0.1 postinstall script 'cross-env NODE_ENV=prod & node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the tessact package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=prod & node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs tessact
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls tessact
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Frontend-Master\npm-debug.log

不要照原样复制节点模块,而是应该在更改OS时再次获得所有节点模块。

删除node_modules文件夹并运行npm install。

顺便说一句:导入带有node_modules文件夹的节点项目不是一个好习惯。 你必须将node_modules放在.gitignore中

您为postInstall设置NODE_ENV的方式不适用于Windows,但适用于Linux。

对于跨平台兼容性,请设置NODE_ENV例如cross-env NODE_ENV=prod &

所以你的package.json脚本看起来像

"scripts": {
    "postinstall": "cross-env NODE_ENV=prod & node -max_old_space_size=8192 ./node_modules/.bin/gulp build:prod",
    "start": "node build/server-bundle.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

当您在Windows中时,也可以使用npm install command再次安装node_modules

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM